package com.yimu.ymblog.jwt.service;

import com.yimu.ymblog.common.domain.dos.UserDO;
import com.yimu.ymblog.common.domain.dos.UserRoleDO;
import com.yimu.ymblog.common.domain.mapper.UserMapper;
import com.yimu.ymblog.common.domain.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查用户表
        UserDO userDO = userMapper.findByUsername(username);

        // 判断用户是否存在
        if (Objects.isNull(userDO)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 判断用户状态
        Integer status = userDO.getStatus();
        if (status == 1) {
            throw new DisabledException("用户被禁用");
        }

        // 根据用户名查询用户角色
        List<UserRoleDO> roleDOS = userRoleMapper.selectByUsername(username);
        String[] roleArr = null;

        // 只要角色不为空，就将角色对象集合拿出来映射成角色名称集合然后转数组
        if (!CollectionUtils.isEmpty(roleDOS)) {
            // 将该用户名所拥有的角色转成角色集合 然后再转数组
            List<String> roles = roleDOS.stream().map(item -> item.getRole()).collect(Collectors.toList());
            roleArr = roles.toArray(new String[roles.size()]);
        }

        // authorities 用于指定角色，这里写死为 ADMIN 管理员
        return User.withUsername(userDO.getUsername())
                .password(userDO.getPassword())
                .authorities(roleArr)
                .build();
    }

}